#!/usr/bin/python
# Main SE Enforcing module
# Importing packages
import os, sys, string, subprocess, re
from ConfigParser import ConfigParser

# Setting up application path
path = "/media/SUPUNZ/assign/"

# Checking and enabling SELinux
subprocess.call([path+'/seen.sh'], shell=True)

# Getting argument
arg = sys.argv[1]

# Parsing Main config file
cfile = path+"config"
config = ConfigParser()
config.readfp(open(cfile))

# Directory Scanning and re-labling
def directoryFix(sname,path):
	# Read configuration
	dconfig = ConfigParser()
	dconfig.readfp(open(path+sname+".data"))

	name = dconfig.get('prog', 'name')
	pathreg = dconfig.get('directory', 'path-reg')
	expath = dconfig.get('directory', 'path-exclude')
	context = dconfig.get('directory', 'context')
	# For all paths fixing context
	for item in pathreg.split(','):
		print path+sname
		with open(path+'configs/'+sname+'.conf', 'r') as inF:
                	for line in inF:
                        	if item in line:
                                	ppath = line.split(item)[1]
                                	ppath = re.findall(r'\".+\"', ppath)
                                	if ppath:
                                        	flag="false"
                                        	nppath = ppath[0]
                                        	nppath = nppath.replace('"', '')
                                        	for exitem in expath.split(','):
                                                	if exitem in nppath:
                                                        	flag="true"
                                        	if flag is "false":
                                                	subprocess.call ([path+'contextfix.sh '+context+' '+nppath+' '+name], shell=True)
							print "Calling subprocess"

# Initializing requested services
def serviceInit(sname,path):
	sconfig = ConfigParser()
	sconfig.readfp(open(path+sname+".data"))
	conf = sconfig.get('prog', 'conf')
	mod = sconfig.get('prog', 'module')
	modules = mod.split(',')
	# Getting and Cleaning Config file
	subprocess.call([path+'cleanconf.sh'+' '+conf+' '+path+'configs/'+sname+'.conf'], shell=True)
	# Checking what modules are supported
	if "directory" in modules: 
		print "Directory context updating module available. Re-Configuring ..."
		directoryFix(sname,path)		
	if "port" in modules:
		print "Port updating module available. Re-Configuring ..."
#		portFix(sname)

# Getting available services
serv = config.get('core', 'services')
services = serv.split(',')

# Called services
if arg in "all":
	for service in services:
		serviceInit(service,path)
elif arg in services:
	serviceInit(arg,path)
else:
	print "Please check available services or use 'all' for scanning all services"

